package com.dmbjz.consumer;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.dmbjz.config.RabbitConfig;
import com.dmbjz.dao.RewardDao;
import com.dmbjz.entity.dto.OrderMessageDTO;
import com.dmbjz.entity.po.RewardPO;
import com.dmbjz.enummeration.RewardStatus;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

import static com.dmbjz.enummeration.OrderStatus.ORDER_CREATED;


/* 餐厅监听器 */
@Component
@Slf4j
public class RewardConsumer {

    @Autowired
    private RewardDao rewardDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /* 处理订单 */
    @RabbitListener(queues = RabbitConfig.REWARD_QUEUE,containerFactory = "rabbitListenerContainerFactory")
    public void orderMessage(Message message, Channel channel) throws IOException {

        String bodyStr = new String(message.getBody());
        OrderMessageDTO messageDTO = JSON.parseObject(bodyStr, OrderMessageDTO.class);
        log.info("奖励服务获取到消息:{}"+messageDTO);

        /* 奖励落库 */
        RewardPO rewardPO = new RewardPO();
        rewardPO.setId(IdUtil.fastSimpleUUID());
        rewardPO.setOrderId(messageDTO.getOrderID());
        rewardPO.setStatus(RewardStatus.SUCCESS);
        rewardPO.setAmount(messageDTO.getPrice());
        rewardPO.setDate(LocalDateTime.now());
        rewardDao.insert(rewardPO);

        /* 更新订单消息数据 */
        messageDTO.setRewardId(rewardPO.getId());
        messageDTO.setOrderStatus(ORDER_CREATED);

        /* 发送消息 */
        MessageProperties properties = new MessageProperties();
        properties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        properties.setContentEncoding("utf-8");
        String jsonMsg = JSON.toJSONString(messageDTO);
        Message sendMsg = new Message(jsonMsg.getBytes(StandardCharsets.UTF_8),properties);

        CorrelationData correlationData = new CorrelationData();
        ReturnedMessage returnedMessage = new ReturnedMessage(sendMsg,300,"餐厅收到订单消息，发送给订单交换机",
                RabbitConfig.REWARD_EXCHANGE,
                "key.order");
        correlationData.setReturned(returnedMessage);
        correlationData.setId(messageDTO.getOrderID());     //设置订单ID

        rabbitTemplate.convertAndSend(RabbitConfig.REWARD_EXCHANGE,"key.order",sendMsg,correlationData);


        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);        //手动消息应答

    }


}
